package com.example.plugin.hook;

import android.annotation.TargetApi;
import android.content.ClipData;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * author: zhouyh
 * created on: 2/1/21 5:20 PM
 * description:伪造的剪切板系统服务
 */
public class ClipBoardBinderHookHandler implements InvocationHandler {


    private static final String TAG = ClipBoardBinderHookHandler.class.getSimpleName();


    //原始的Service对象(IInterface)
    Object base;

    public ClipBoardBinderHookHandler(IBinder base,Class<?> stubClass) {
        try {
            Method asInterfaceMethod  = stubClass.getDeclaredMethod("asInterface", IBinder.class);
            //IClipboard.Stub.asInterface(base);
            this.base = asInterfaceMethod.invoke(null,base);
        } catch (Exception e) {
           throw new RuntimeException("hook failed");
        }
    }


    @TargetApi(Build.VERSION_CODES.HONEYCOMB)
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        /**
         * 用动态代理的方式Hook掉了hasPrimaryClip()，getPrimaryClip()
         */
        // 欺骗系统,使之认为剪切版上一直有内容
        if ("hasPrimaryClip".equals(method.getName())){
            return true;
        }

        // 把剪切版的内容替换为 "you are hooked"
        if ("getPrimaryClip".equals(method.getName())){
            Log.i(TAG,"getPrimaryClip hook");
            return ClipData.newPlainText(null,"you are hooked");
        }
        return method.invoke(base,args);
    }
}
